<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <title>新增页面</title>
    <link rel="stylesheet" href="/app/admin/component/pear/css/pear.css"/>
    <link rel="stylesheet" href="/app/admin/admin/css/reset.css"/>
</head>
<style>
    .layui-input-wrap60 {
        width: 60px !important;
        line-height: 20px !important;
    }
</style>
<body>

<form class="layui-form" action="">

    <div class="mainBox">
        <div class="main-container mr-5">

            <div class="layui-form-item">
                <label class="layui-form-label required">下载器品牌</label>
                <div class="layui-input-block">
                    <div name="brand" id="brand" required value=""></div>
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label required">标题</label>
                <div class="layui-input-block">
                    <input type="text" name="title" value="" required lay-verify="required" class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label required">协议主机</label>
                <div class="layui-input-block">
                    <input type="text" name="hostname" value="" required lay-verify="required"
                           placeholder="协议主机端口，例：http://192.168.1.2:9091" class="layui-input">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label required">接入点
                    <a href="https://doc.iyuu.cn/guide/downloader#接入点" target="_blank" rel="noopener noreferrer">
                        <i class="layui-icon layui-icon-help layui-font-red"></i>
                    </a>
                </label>
                <div class="layui-input-block">
                    <input type="text" name="endpoint" value="" required lay-verify="required" class="layui-input"
                           id="endpoint">
                </div>
            </div>


            <div class="layui-form-item">
                <label class="layui-form-label required">用户名</label>
                <div class="layui-input-block">
                    <input type="text" name="username" value="" required lay-verify="required"
                           class="layui-input" autocomplete="off">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label required">密码</label>
                <div class="layui-input-block">
                    <input type="text" name="password" value="" lay-affix="eye" required
                           lay-verify="required"
                           class="layui-input" autocomplete="off">
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">监控文件夹</label>
                <div class="layui-input-group">
                    <input type="text" name="watch_path" value="" class="layui-input"
                           placeholder="通过放入.torrent创建任务">
                    <div class="layui-input-suffix">
                        <a href="https://doc.iyuu.cn/guide/downloader#监控文件夹" target="_blank"
                           rel="noopener noreferrer">
                            <i class="layui-icon layui-icon-help layui-font-red"></i>
                        </a>
                    </div>
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">资源文件夹</label>
                <div class="layui-input-group">
                    <input type="text" name="save_path" value="" class="layui-input" placeholder="即保存路径、保存目录">
                    <div class="layui-input-suffix">
                        <a href="https://doc.iyuu.cn/guide/transfer-torrent#资源文件夹" target="_blank"
                           rel="noopener noreferrer">
                            <i class="layui-icon layui-icon-help layui-font-red"></i>
                        </a>
                    </div>
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">种子文件夹</label>
                <div class="layui-input-group">
                    <input type="text" name="torrent_path" value="" class="layui-input"
                           placeholder=".torrent存放的目录">
                    <div class="layui-input-suffix">
                        <a href="https://doc.iyuu.cn/guide/transfer-torrent#种子文件夹" target="_blank"
                           rel="noopener noreferrer">
                            <i class="layui-icon layui-icon-help layui-font-red"></i>
                        </a>
                    </div>
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">校验后做种</label>
                <div class="layui-input-inline layui-input-wrap60">
                    <input type="checkbox" id="seeding_after_completed" lay-filter="seeding_after_completed"
                           lay-skin="switch"/>
                    <input type="text" style="display:none" name="seeding_after_completed" value="1"/>
                </div>
                <div class="layui-form-mid layui-text-em layui-word-aux">辅种的种子在校验完成后自动做种</div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">调试</label>
                <div class="layui-input-block">
                    <input type="checkbox" id="is_debug" lay-filter="is_debug" lay-skin="switch"/>
                    <input type="text" style="display:none" name="is_debug" value="0"/>
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">默认下载器</label>
                <div class="layui-input-block">
                    <input type="checkbox" id="is_default" lay-filter="is_default" lay-skin="switch"/>
                    <input type="text" style="display:none" name="is_default" value="0"/>
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">启用</label>
                <div class="layui-input-block">
                    <input type="checkbox" id="enabled" lay-filter="enabled" lay-skin="switch"/>
                    <input type="text" style="display:none" name="enabled" value="1"/>
                </div>
            </div>

            <div class="layui-form-item" id="support_root_folder">
                <label class="layui-form-label">创建多文件子目录</label>
                <div class="layui-input-inline layui-input-wrap60">
                    <input type="checkbox" id="root_folder" lay-filter="root_folder" lay-skin="switch"/>
                    <input type="text" style="display:none" name="root_folder" value="1"/>
                </div>
                <div class="layui-form-mid layui-text-em layui-word-aux">仅qBittorrent支持</div>
            </div>

        </div>
    </div>

    <div class="bottom">
        <div class="button-container">
            <button class="layui-icon layui-icon-help" id="helpButton"></button>
            <button type="submit" class="pear-btn pear-btn-primary pear-btn-md" lay-submit=""
                    lay-filter="save">
                提交
            </button>
            <!--<button type="reset" class="pear-btn pear-btn-md" lay-on="reset">
                重置
            </button>-->
        </div>
    </div>

</form>

<script src="/app/admin/component/layui/layui.js?v=2.8.12"></script>
<script src="/app/admin/component/pear/pear.js"></script>
<script src="/app/admin/admin/js/permission.js"></script>
<script>
        // 点击帮助按钮跳转到新页面
        document.getElementById("helpButton").addEventListener("click", function () {
            var helpPageUrl = "https://doc.iyuu.cn/guide/downloader";
            window.open(helpPageUrl, "_blank");
        });
    /**
     * 帮助
     * @type {{qq_qun: string}}
     */
    window.IYUU_HELP = JSON.parse(localStorage.getItem('IYUU_HELP'));
    // 相关接口
    const PRIMARY_KEY = "id";
    const SELECT_API = "/admin/client/select" + location.search;
    const UPDATE_API = "/admin/client/update";
    const INSERT_API = "/admin/client/insert";

    layui.use(["jquery", "xmSelect", "popup", "util"], function () {
        let $ = layui.$;
        let popup = layui.popup;
        let util = layui.util;
        layui.form.verify({
            url: [/(^$)|(^#)|(^http(s*):\/\/[^\s]+\.[^\s]+)/, "链接格式不正确"],
        });
        const client_id = layui.url().search[PRIMARY_KEY] || '';
        const brand = layui.url().search['brand'] || '';
        if (brand) {
            layui.$("#brand").attr("value", brand);
        }

        if (client_id) {
            // 获取数据库记录
            $.ajax({
                url: SELECT_API,
                dataType: "json",
                success: function (res) {

                    // 给表单初始化数据
                    layui.each(res.data[0], function (key, value) {
                        let obj = $('*[name="' + key + '"]');

                        if (typeof obj[0] === "undefined" || !obj[0].nodeName) return;
                        if (obj[0].nodeName.toLowerCase() === "textarea") {
                            obj.val(value);
                        } else {
                            obj.attr("value", value);
                            obj[0].value = value;
                        }
                    });

                    render_field();

                    // ajax返回失败
                    if (res.code) {
                        layui.popup.failure(res.msg);
                    }
                }
            });
        } else {
            render_field();
        }

        // 字段 下载器品牌 brand
        layui.$.ajax({
            url: "/admin/enums/client",
            dataType: "json",
            success: function (res) {
                let value = layui.$("#brand").attr("value");
                // 创建多文件子目录
                support_root_folder(value);

                let initValue = value ? value.split(",") : [];
                let brandSelect = layui.xmSelect.render({
                    el: "#brand",
                    name: "brand",
                    initValue: initValue,
                    filterable: true,
                    data: res.data,
                    model: {"icon": "hidden", "label": {"type": "text"}},
                    clickClose: true,
                    radio: true,
                    layVerify: "required",
                    disabled: Boolean(client_id),
                    on: function (data) {
                        //arr:  当前多选已选中的数据
                        let arr = data.arr;
                        //change, 此次选择变化的数据,数组
                        let change = data.change;
                        //isAdd, 此次操作是新增还是删除
                        let isAdd = data.isAdd;
                        if (isAdd) {
                            let item = change.shift();
                            console.log(item)
                            let brand = item.value;

                            // 创建多文件子目录
                            support_root_folder(brand);
                            // 接入点
                            endpoint_transmission(brand);
                            //选完后禁用
                            brandSelect.update({disabled: true});
                        }
                    },
                });

                if (res.code) {
                    layui.popup.failure(res.msg);
                }
            }
        });

        /**
         * 创建多文件子目录
         * @param {string} brand
         */
        function support_root_folder(brand = '') {
            let support_root_folder_elem = layui.$("#support_root_folder");
            if ('qBittorrent' !== brand) {
                support_root_folder_elem.hide();
            } else {
                support_root_folder_elem.show();
            }
        }

        /**
         * 接入点transmission
         * @param {string} brand
         */
        function endpoint_transmission(brand = '') {
            const ENDPOINT_RPC = '/transmission/rpc';
            let endpoint_elem = layui.$('input[name="endpoint"]');
            if ('transmission' === brand) {
                endpoint_elem.val(ENDPOINT_RPC);
            } else {
                endpoint_elem.val('/');
            }
        }

        /**
         * 渲染其他字段
         */
        function render_field() {
            // 字段 创建多文件子目录 root_folder
            layui.use(["form"], function () {
                layui.$("#root_folder").attr("checked", layui.$('input[name="root_folder"]').val() != 0);
                layui.form.render();
                layui.form.on("switch(root_folder)", function (data) {
                    layui.$('input[name="root_folder"]').val(this.checked ? 1 : 0);
                });
            })

            // 字段 调试 is_debug
            layui.use(["form"], function () {
                layui.$("#is_debug").attr("checked", layui.$('input[name="is_debug"]').val() != 0);
                layui.form.render();
                layui.form.on("switch(is_debug)", function (data) {
                    layui.$('input[name="is_debug"]').val(this.checked ? 1 : 0);
                });
            })

            // 字段 默认 is_default
            layui.use(["form"], function () {
                layui.$("#is_default").attr("checked", layui.$('input[name="is_default"]').val() != 0);
                layui.form.render();
                layui.form.on("switch(is_default)", function (data) {
                    layui.$('input[name="is_default"]').val(this.checked ? 1 : 0);
                });
            })

            // 字段 启用 enabled
            layui.use(["form"], function () {
                layui.$("#enabled").attr("checked", layui.$('input[name="enabled"]').val() != 0);
                layui.form.render();
                layui.form.on("switch(enabled)", function (data) {
                    layui.$('input[name="enabled"]').val(this.checked ? 1 : 0);
                });
            })

            // 字段 校验后做种 seeding_after_completed
            layui.use(["form"], function () {
                layui.$("#seeding_after_completed").attr("checked", layui.$('input[name="seeding_after_completed"]').val() != 0);
                layui.form.render();
                layui.form.on("switch(seeding_after_completed)", function (data) {
                    layui.$('input[name="seeding_after_completed"]').val(this.checked ? 1 : 0);
                });
            })
        }

        /**
         * 提交事件
         */
        // 字段验证允许为空
        layui.form.verify({
            phone: [/(^$)|^1\d{10}$/, "请输入正确的手机号"],
            email: [/(^$)|^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/, "邮箱格式不正确"],
            url: [/(^$)|(^#)|(^http(s*):\/\/[^\s]+\.[^\s]+)/, "链接格式不正确"],
            number: [/(^$)|^\d+$/, '只能填写数字'],
            date: [/(^$)|^(\d{4})[-\/](\d{1}|0\d{1}|1[0-2])([-\/](\d{1}|0\d{1}|[1-2][0-9]|3[0-1]))*$/, "日期格式不正确"],
            identity: [/(^$)|(^\d{15}$)|(^\d{17}(x|X|\d)$)/, "请输入正确的身份证号"]
        });
        layui.form.on("submit(save)", function (data) {
            if (client_id) {
                data.field[PRIMARY_KEY] = client_id;
            }

            layui.$.ajax({
                url: client_id ? UPDATE_API : INSERT_API,
                type: "POST",
                dateType: "json",
                data: data.field,
                success: function (res) {
                    if (res.code) {
                        return layui.popup.failure(res.msg);
                    }
                    return layui.popup.success("操作成功", function () {
                        parent.refreshTable();
                        parent.layer.close(parent.layer.getFrameIndex(window.name));
                    });
                }
            });
            return false;
        });
    });
</script>

</body>
</html>
